<?php

namespace App\Http\Helpers;

use Illuminate\Http\JsonResponse;

trait ApiResponse
{
    /**
     * StatusResponse Data
     * @returns JsonResponse
     */
    public function respond ($data): JsonResponse
    {
        return response()->json($data);
    }

    /**
     * Set A StatusResponse Json
     * @returns JsonResponse
     */
    public function status($status, $msg, $data = null): JsonResponse
    {
        $d = [
            'code' => $status,
            'message' => $msg
        ];
        if ($data) {
            $d['data'] = $data;
        }
        return $this->respond($d);
    }

    /**
     * Get A Successful StatusResponse
     * @returns JsonResponse
     */
    public function success ($data = null): JsonResponse
    {
        $status = StatusResponse::OK;
        return $this->status($status[0], $status[1], $data);
    }

    /**
     * Use Code And Message Get A Failed StatusResponse
     * @returns JsonResponse
     */
    public function fail ($code, $msg, $data = null): JsonResponse
    {
        return $this->status($code, $msg, $data);
    }

    /**
     * 使用变量数组返回信息
     * @param $arr
     * @param null $data
     * @return JsonResponse
     */
    public function failWithArr ($arr, $data=null) : JsonResponse
    {
        return $this->status($arr[0], $arr[1], $data);
    }

    /**
     * 未知错误
     * @return JsonResponse
     */
    public function unknown_err () :JsonResponse
    {
        return $this->status(StatusResponse::UNKNOWN_ERROR[0], StatusResponse::UNKNOWN_ERROR[1]);
    }
}
